package cn.wolfcode.shop.exception;

import cn.wolfcode.shop.result.CodeMsg;
import cn.wolfcode.shop.result.Result;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by wolfcode-lanxw
 */
@ControllerAdvice
public class ExceptionHanlder {
    @ExceptionHandler({BindException.class,GlobalException.class})
    @ResponseBody
    public Result<CodeMsg> handlerException(Exception ex){
        if(ex instanceof BindException){
            BindException e = (BindException) ex;
            String defaultMessage = e.getAllErrors().get(0).getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(defaultMessage));
        }else if(ex instanceof GlobalException){
            GlobalException e = (GlobalException) ex;
            return Result.error(e.getCodeMsg());
        }
        return Result.error(CodeMsg.SERVER_ERROR);
    }
}
